package com.chap16;

/**
 * <p>
 * <code>MonitorThread</code>
 * </p>
 *
 * @author junbao3
 * TODO
 * @date 2023-04-24 9:13
 * Copyright (C) 2021 IFlyTek. All rights reserved.
 */
public class MonitorThread extends Thread {
    private volatile boolean terminated = false;

    @Override
    public void run() {
        while (!terminated){
            //执行监控操作
            System.out.println("监控线程正在执行监控操作...");
        }
        try {
            //监控程序每隔一秒收集一个数据
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            //检查中断状态
            System.out.println("监控线程被中断，准备退出...");
            Thread.currentThread().interrupt();
            e.printStackTrace();
        }
        //执行清理操作
        System.out.println("监控线程正在执行清理操作...");
        releaseResources();

    }
    private void releaseResources() {
        System.out.println("监控线程正在释放资源和进行必要的清理工作");

    }

    public void terminate(){
        //设置标志变量为true 并等待一段时间
        terminated = true;
        try {
            join(5000);//等待5秒，期间监控线程会检查terminated的状态
            //监控线程调join，主线程会等待5秒，等5秒还没执行完，主线程继续执行
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public static void main(String[] args) throws InterruptedException {
        MonitorThread thread = new MonitorThread();
        //启动监控线程
        thread.start();
        //主线程休眠期间 监控线程执行监控操作
        Thread.sleep(10000);
        //终止监控线程
        thread.terminate();

        Thread.sleep(10000);
    }
}
